package com.minelx.serverandclient.stream.divider;

import com.minelx.serverandclient.stream.Indexer;
import com.minelx.serverandclient.stream.divider.Divider;

public class IndexedDivider implements Divider {

	private final Indexer source;

	private final byte[] cacheBytes;

	private int currentIndex;

	private boolean preloaded;

	private int indexedLength;

	public IndexedDivider(Indexer source, int dividedLength) {
		cacheBytes = new byte[dividedLength];
		this.source = source;
	}

	@Override
	public byte[] next() {
		if (preloaded) {
			preloaded = false;
			return cacheBytes;
		}
		moveToNext();
		return cacheBytes;
	}

	@Override
	public boolean hasNext() {
		if (!preloaded) {
			moveToNext();
			preloaded = true;
		}
		return indexedCount() != Indexer.EOF;
	}

	@Override
	public int indexedCount() {
		return indexedLength;
	}

	private void moveToNext() {
		indexedLength = source.indexCount(currentIndex, cacheBytes);
		currentIndex += indexedLength;
	}
}
